package capaDatos;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import utiles.UIDGenerator;
import capaLogica.Noticia;
import capaLogica.Voto;

public class VotoDAO {
	/**
	 * Atributo que crea la conexion a la bd
	 */
	private Connection conn;
	
	/**
	 * Constructor de la clase
	 */
	public VotoDAO(){
		conn = (Connection) ConnectionManager.getInstance().checkOut();
	}
	
	@Override
	 protected void finalize() {
       ConnectionManager.getInstance().checkIn(conn);
	}
	
	 public void insertarVoto(Voto v) {
			String sql = "INSERT INTO voto (idVoto,idUsuario,idEvento,fecha) VALUES (?,?,?,?) ";
			PreparedStatement stmt = null;
			
			try {
				stmt = conn.prepareStatement(sql);
				v.setIdVoto(UIDGenerator.getInstance().getKey());
				
				java.util.Date fechaNoticia= v.getFechaVotacion();
	            
				stmt.setString(1, v.getIdVoto());
				stmt.setString(2, v.getIdUsuario());
				stmt.setString(3, v.getIdEvento());
				stmt.setDate(4, new java.sql.Date(fechaNoticia.getTime()));
			
				stmt.executeUpdate();

			} catch (SQLException e) {
				System.out.println("Message: " + e.getMessage());
				System.out.println("SQLState: " + e.getSQLState());
				System.out.println("ErrorCode: " + e.getErrorCode());
			} finally {
				try {
					if (stmt != null) {
						stmt.close();
						
					}
				} catch (SQLException e) {
				}
			}
		}
	 
	 public boolean comprobarVotado(String idEvento, String idUsuario){
		 String sql = "Select * FROM voto WHERE (idEvento = ?)  AND (idUsuario = ?)";
		 PreparedStatement stmt = null;
	        ResultSet result = null;
	        Boolean p = false;
			 try {
		            stmt = conn.prepareStatement(sql);
		            stmt.setString(1, idEvento);
		            stmt.setString(2, idUsuario);
		            result = stmt.executeQuery();

		            if ( result.next() ){
			            p=true;
		            }

			} catch (SQLException e) {
				System.out.println("Message: " + e.getMessage());
				System.out.println("SQLState: " + e.getSQLState());
				System.out.println("ErrorCode: " + e.getErrorCode());
			} finally {
				try {
					if (stmt != null) {
						stmt.close();
						
					}
				} catch (SQLException e) {
				}
			}
			return p;
	 }
	 
}
